package cn.gongwebo.payview.temp;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.gongwebo.payview.R;

/**
 * Created by GongWenBo on 2017/12/13.
 */

public class ProgressDialog extends DialogFragment {

    private static final String TAG = "ProgressDialog";

    @BindView(R.id.pv)
    ProgressView mPv;
    @BindView(R.id.tv_loading)
    TextView     mTvLoading;
    private String loading = "loading...";
    private long   TIME    = 500;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int length = mTvLoading.getText().length();
            if (length < loading.length()) {
                mTvLoading.setText(loading.substring(0, length + 1));
            } else {
                mTvLoading.setText(loading.substring(0, loading.length() - 3));
            }
            mHandler.sendEmptyMessageDelayed(0, TIME);
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        setCancelable(false);
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.dialog_progress, container);
        ButterKnife.bind(this, view);
        mTvLoading.setText(loading.substring(0, loading.length() - 3));
        mHandler.sendEmptyMessageDelayed(0, TIME);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT);
            getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        }
    }

    public void setProgress(int progress){
        mPv.setProgress(progress);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mHandler.removeCallbacksAndMessages(null);
        Log.d(TAG, "onDismiss: ");
    }

}
